package cn.tansanqinger.agency;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface IMessageService{
    void send();
}
class MessageServiceImpl implements IMessageService{
    @Override
    public void send(){
        System.out.println("发送消息：www.tansanqinger.cn");
    }
}
class MessageServiceImplProxy implements InvocationHandler {
    Object object;//正常业务实现
    public Object bind(Object object) {
        this.object = object;
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this);
    }

    public boolean connect(){
        System.out.println("发送消息通道打开……");
        return true;
    }
    public void close(){
        System.out.println("关闭消息发送通道……");
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object returnValue = null;
        if(this.connect()){
            returnValue = method.invoke(this.object, args);
            this.close();
        }
        return returnValue;
    }
}
class DynamicProxyFactory{//使用工厂设计模式
    private DynamicProxyFactory(){}//构造方法私有化
    public static IMessageService getInstance(){
        return (IMessageService)new MessageServiceImplProxy().bind(new MessageServiceImpl());
    }
}
public class DynamicProxy {
    public static void main(String[] args) {
        IMessageService service = DynamicProxyFactory.getInstance();
        service.send();
    }
}
